<template>
  <div>
    <el-card class="filter-container" shadow="never">
      <div>
        <i class="el-icon-search"></i>
        <span>筛选搜索</span>
        <el-button style="float:right;
          ;margin-right: 30px" type="primary" @click="handleSearch()">
          查询
        </el-button>
        <el-button style="float:right;margin-right: 15px" @click="handleResetSearch()">
          重置
        </el-button>
      </div>

      <div style="margin-top: 30px; ">
        <el-form style="display: inline-block;">
          <div style="display: inline-block;margin-left:40px">
            <el-form-item label="小组名：">
              <el-input class="input-width" v-model="searchForm.groupName" placeholder="小组名"></el-input>
            </el-form-item>
          </div>
          <div style="display: inline-block;margin-left:40px">
            <el-form-item prop="groupStatus" label="小组状态：">
              <el-select class="input-width" v-model="searchForm.status" placeholder="选择状态" style="width: 200px;" clearable>
                  <el-option style="width: 200px;" :value="0" label="待分配">
                    </el-option>
                      <el-option style="width: 200px;" :value="1" label="已分配">
                    </el-option>
                </el-select>
            </el-form-item>
          </div>
        </el-form>
      </div>
    </el-card>
  </div>
  <div style="margin: 20px;">
    <el-table ref="multipleTable" :data="tableData.list" tooltip-effect="dark" border style="width: 100%" stripe>

      <el-table-column prop="groupName" label="小组名" align="center"/>
      <el-table-column prop="groupLeader" label="小组长名" align="center"/>
      <el-table-column prop="groupStatus" label="分配状态" align="center">
        <template #default="scope">
            <el-tag v-if="scope.row.groupStatus == 0" :type="'danger'">
              待分配
            </el-tag>
            <el-tag v-else-if="scope.row.groupStatus == 1">
              已分配
            </el-tag>
          </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" min-width="120" class="operate-button-container" align="center">
        <template #default="scope">
        <el-button  type="warning" size="small" @click="open(scope.row)">
          编辑
        </el-button>
        <el-button size="small" @click="() => handleDelete(scope.row)" type="danger">删除
        </el-button>
      </template>
      </el-table-column>
      <el-table-column prop="memberName" label="小组成员"  align="center">
      <template #default="{ row }">
        <div>
        <!-- 遍历 row.members 数组 -->
        <div v-for="(member, index) in row.members" :key="index" style="display: inline;">
          <!-- 只显示 memberName -->
         <span>{{ member.memberName }}  </span>
         <span v-if="index < row.members.length - 1">, </span>
        </div>
      </div>
      </template>
      </el-table-column>
      <el-table-column  label="小组成员操作" align="center">
        <template #default="scope">
          <el-button plain @click="groupMember(scope.row)" size="small" color="#626aef" :dark="isDark">
          编辑小组成员
          </el-button>
        </template>   
      </el-table-column> 
    </el-table>
    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pageNum"
      :page-sizes="[5, 20, 50, 100]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
  </div>
  <!-- 编辑小组成员对话框 -->
  <el-dialog title="编辑小组成员" v-model="groupMeberData" width="350px">
    <el-dropdown placement="bottom">
      <el-button type="success" plain> 添加工人 </el-button>
      <template #dropdown>
        <el-dropdown-menu>
          <el-table :data="staffNoGroupList">
              <el-table-column prop="userName" label="工人姓名" align="center"></el-table-column>
              <el-table-column label="添加工人" align="center">
                <template #default="scope">
                  <el-button size="small" @click="AddRowMember(scope.row)" :icon="Plus" circle type="success"></el-button>
                </template>
              </el-table-column>
          </el-table>
        </el-dropdown-menu>
      </template>
    </el-dropdown>
    <!-- <el-button type="success" size="small" round @click="addMember()">添加工人</el-button> -->
    <div>
      <el-table ref="multipleTable" :data="memberList" tooltip-effect="dark"  style="width:260px" stripe>
        <el-table-column prop="memberName" label="工人姓名" width="160" align="center"/>
        <el-table-column label="移除成员" width="100" align="center">
          <template #default="scope">
          <el-button size="small" @click="deleteRowMember(scope.row)" :icon="Delete" circle type="danger"></el-button>
        </template>
        </el-table-column>
      </el-table>
    </div>
  </el-dialog>
  <el-dialog
    v-model="dialogFormVisible1"
    :before-close="beforeClose"
    title="编辑小组"
  >
  <el-table >
    <el-table-column prop="groupName" label="所在小组"></el-table-column>
    <el-table-column prop="groupName" label="成员姓名"></el-table-column>
    <el-table-column prop="groupName" label="联系方式"></el-table-column>
  </el-table>

  </el-dialog>
  <el-dialog 
    v-model="dialogFormVisible"
    :before-close="beforeClose"
    title="编辑小组"
  >
    <el-form
      ref="formRef"
      :model="updateForm"
      :rules="rules"
      >
      <el-form-item prop="groupName" label="小组名：">
        <el-input v-model="updateForm.name"/>
      </el-form-item>
      <!-- <el-form-item prop="groupLeader" label="小组长名：">
        <el-input v-model="updateForm.groupLeader"/>
      </el-form-item> -->
      <el-form-item prop="groupStatus" label="小组状态：">
        <el-select class="input-width" v-model="updateForm.status" placeholder="选择状态" clearable>
            <el-option style="width: 200px;" :value="0" label="待分配">
              </el-option>
                <el-option style="width: 200px;" :value="1" label="已分配">
              </el-option>
          </el-select>
      </el-form-item>
      <el-form-item prop="groupNote" label="备注：">
        <el-input v-model="updateForm.note"/>
      </el-form-item>
    </el-form>
    <el-button type="primary" style="margin-left: 50%;" @click="confirm()">提交</el-button>
  </el-dialog>
  <el-pagination
      v-model:currentPage="searchForm.pageNum"
      v-model:page-size="searchForm.pageSize"
      background
      layout="prev, pager, next, total, sizes"
      :page-sizes="[10,20,50]"
      :size="size"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
      :total="tableData.total"
      :current-page ="searchForm.pageNum"
      :page-size="searchForm.pageSize"
    />
</template>
<script setup>
import { nextTick ,ref, reactive, onMounted, VueElement} from 'vue';
import { groupList, groupSearch,updateGroup ,deleteGroup,getStaffNoGroup} from '../../../api';
import { deleteMember,getGroup,AddMember } from '../../../api';
import { ElMessage } from 'element-plus';
import {Delete,Plus} from '@element-plus/icons-vue'

const groupMeberData = ref(false)
const memberList = ref([])
const staffNoGroupList = ref([])
const deleteMemberData ={
  groupId: '',
  memberIds: [],
}

const groupMember = (row) => {
  console.log('row:', row)
  console.log('groupId:', row.groupId)
  deleteMemberData.groupId=row.groupId
  console.log('deleteMemberData.groupId:',deleteMemberData.groupId)
  groupMeberData.value = true
  getMemberList(row.groupId)
  const members = row.members
  console.log('members:',members)  
  deleteMemberData.memberIds = members.map(item => item.memberId);
  console.log(deleteMemberData.memberIds);
};

const getMemberList = async(groupId) =>{
  const response = await getGroup(groupId)
  memberList.value = response.data.members
  console.log("memberList:")
  console.log(memberList.value)
  console.log(memberList)
}

const getStaffNoGroupList = async() =>{
  const response = await getStaffNoGroup()
  staffNoGroupList.value = response.data
  console.log(staffNoGroupList.value)
}

// // 当前页变化处理
const handleCurrentChange = (val) => {

tableData.pageNum = val; // 更新当前页码
getData();// 重新获取数据
};

// 页面大小变化处理
const handleSizeChange = (val) => {
tableData.pageSize = val; // 更新每页条目数
getData(); // 重新获取数据
};

//查询数据
const handleSearch = async () => {
  
  console.log('查询内容1', searchForm)
  let res = await groupList(searchForm)
  console.log('查询内容', res.data)
  tableData.list = res.data.list
  console.log('返回数据',tableData.list)

    //tableData.totalPage = total
    console.log('total',res.data.totalPage)
    let total = res.data.totalPage
    tableData.totalPage = res.data.totalPage
    tableData.total =Number(res.data.total) 
    tableData.pageNum = res.data.pageNum

    console.log('totalzongde', tableData.total)
    console.log('zongde',tableData)
  //console.log('查询结果', tableData.list.value)
}

const deleteRowMember = async(row)=>{
  console.log(row.memberId)
  try {
    await ElMessageBox.confirm('是否要将该成员移除本组', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    await deleteMember(deleteMemberData.groupId,row.memberId);
    ElMessage({
      message: '移除成功',
      type: 'success',
      duration: 1000
    });
    groupMember();
    getList();
  } catch (error) {
    // Handle cancel or error
  } 
}

const AddRowMember = async(row)=>{
  console.log(row)
  console.log(row.userId)
  console.log(deleteMemberData.groupId)
  try {
    await ElMessageBox.confirm('是否要将该成员添加至本组', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    await AddMember(deleteMemberData.groupId,row.userId);
    ElMessage({
      message: '添加成功',
      type: 'success',
      duration: 1000
    });
    groupMember();
    getList();
  } catch (error) {
    // Handle cancel or error
  } 
}


//数据表数据
const tableData = reactive({
  list: [],
  pageNum:'',
  pageSize:'',
  total:'',
  totalPage:''
})

onMounted(() => {
  getList(),
  getStaffNoGroupList()
})

let data ={
  groupName:'',
  pageNum:1,
  pageSize:10,
  status:''
}

const  getList = async () =>{
  const response = await groupList(data)
    console.log("resp",response)
    console.log(data)
    tableData.list = response.data.list
    tableData.total=Number(response.data.total)
    tableData.pageNum = response.data.pageNum
    tableData.pageSize = response.data.pageSize
    console.log('小组成员',tableData.list[0])
}

const rules = reactive({
  groupId:[{required:false,trigger:'blur',messege:'请填写小组编号'}],
  groupName:[{required:false,trigger:'blur',messege:'请填写名字'}],
  groupStatus:[{required:false,trigger:'blur',messege:'请选择状态'}],
  groupNote:[{required:false,trigger:'blur',messege:'备注信息'}],
})


//查询数据
let searchForm = reactive({
  groupName:'',
  status: '', 
  pageNum:1,
  pageSize:10,
    }
)

// //查询数据

// const handleSearch = async () => {
//   console.log('查询内容1', searchForm.value)
//   let res = await groupList(searchForm.value)
//   console.log('查询内容', res.data.list)

//   console.log('000000000', prods)

//   tableData.list = res.data.list;   //返回本条数据
//   console.log('返回数据',tableData.list)

  
// }
//编辑数据
const dialogFormVisible = ref(false)
const formRef = ref()

const updateForm = ref({
  id:'',
  name:'',
  status: '',
  note: ''
})

const open = (rowData = {}) => {
  
  dialogFormVisible.value = true
  console.log('rowData',rowData)
  //弹窗打开form 声称是异步的
  nextTick(() => {
    //如果是编辑
    if (rowData) {
      updateForm.value.id=rowData.groupId
      updateForm.value.name=rowData.groupName
      updateForm.value.status=rowData.groupStatus
      updateForm.value.note=rowData.groupNote
      // Object.assign(updateForm.value, rowData)
      // updateForm.value = rowData
      console.log("这里是获取编辑数据", rowData)
      // updateForm.value.groupId=rowData.groupId
    }
  })
}

const confirm = async () => {
  console.log('更新内容', updateForm)
  console.log('更新内容', updateForm.value)
  //把updateForm.value给列表的第一列
  let res = await updateGroup(updateForm.value);
  console.log('查看一下', updateForm)
  console.log('查看一下2', res)
  // let response = await getProductCategoryList(res.value)
  // console.log('查看结果',  response)
  //console.log(res.code)
  if (res.code == 200) {
    ElMessage({
      message: '修改成功',
      type: 'success',
      duration: 1000
    });
    getList()
  } else {
    ElMessage({
      message: res.message,
      type: 'error',
      duration: 1000
    });
  }
dialogFormVisible.value = false
}

//删除数据
const handleDelete = async (row) => {
  console.log('rowinfo',row.groupId)
  try {
    await ElMessageBox.confirm('是否要将该小组成员移除本小组', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    await deleteGroup(row.groupId);
    //console.log('id',row.groupId)
    ElMessage({
      message: '移除成功',
      type: 'success',
      duration: 1000
    });
    getList();
  } catch (error) {
    // Handle cancel or error
  }
};

</script>
<style lang="less">

</style>